package com.zlq.cn.service.exam;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlq.cn.bootstrap.SignApiBootstrap;
import com.zlq.cn.dto.vo.ExamQuestionImport;
import com.zlq.cn.entity.ExamAnswers;
import com.zlq.cn.entity.ExamQuestions;
import com.zlq.cn.entity.ExamTestPaper;
import com.zlq.cn.entity.FanyiUser;
import com.zlq.cn.enums.QuestionTypeEnum;
import com.zlq.cn.mapper.exam.ExamTestPaperMapper;
import com.zlq.cn.util.ServletUtils;
import com.zlq.cn.util.StringUtils;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhoucl
 * @since 2024-04-10
 */
@Service
public class ExamTestPaperService extends ServiceImpl<ExamTestPaperMapper, ExamTestPaper> {

    @Resource
    private ExamAnswersService examAnswersService;

    @Resource
    private ExamQuestionsService examQuestionsService;

    public Page<ExamTestPaper> page(Page<ExamTestPaper> page, ExamTestPaper param) {
        FanyiUser fanyiUser = SignApiBootstrap.requestFanYiUser();
        return super.lambdaQuery()
                .eq(ExamTestPaper::getImei, fanyiUser.getFanyiUserImei())
                .like(StringUtils.isNotEmpty(param.getTitle()), ExamTestPaper::getTitle, param.getTitle())
                .page(page);
    }

    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public Integer importTestPaper(MultipartFile file, String title) {
        ExamTestPaper examTestPaper = new ExamTestPaper();
        String imei = ServletUtil.getHeader(ServletUtils.getRequest(), "imei", StandardCharsets.UTF_8);
        Assert.notNull(imei, "请先登陆");
        examTestPaper.setImei(imei);
        Workbook book = WorkbookFactory.create(file.getInputStream());
        Row row = book.getSheetAt(0).getRow(0);
        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
            String cellValue = row.getCell(i).getStringCellValue();
            if (StringUtils.isNotBlank(cellValue)) {
                examTestPaper.setTitle(cellValue);
            }
        }
        examTestPaper.setTitle(StringUtils.defaultString(title, examTestPaper.getTitle()));
        examTestPaper.setCreateTime(LocalDateTime.now());
        examTestPaper.setUpdateTime(LocalDateTime.now());
        super.save(examTestPaper);

        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        List<ExamQuestionImport> examQuestionImports = ExcelImportUtil.importExcel(file.getInputStream(), ExamQuestionImport.class, params);
        List<ExamQuestions> examQuestionList = new ArrayList<>();
        List<ExamAnswers> examAnswers = new ArrayList<>();
        for (ExamQuestionImport examQuestionImport : examQuestionImports) {
            if (StringUtils.isBlank(examQuestionImport.getTypeName()) ||
                    StringUtils.isBlank(examQuestionImport.getTitle()) ||
                    StringUtils.isBlank(examQuestionImport.getAnswer())) {
                continue;
            }
            ExamQuestions examQuestions = BeanUtil.copyProperties(examQuestionImport, ExamQuestions.class);
            examQuestions.setType(QuestionTypeEnum.nameToType(examQuestionImport.getTypeName()));
            if (StringUtils.isEmpty(examQuestions.getType())) {
                continue;
            }
            if (QuestionTypeEnum.MULTIPLE.getType().equals(examQuestions.getType())) {
                StringJoiner sj = new StringJoiner(",");
                for (char c : examQuestions.getAnswer().toCharArray()) {
                    sj.add(c + "");
                }
                examQuestions.setAnswer(sj.toString());
            } else if (QuestionTypeEnum.COMPLETION.getType().equals(examQuestions.getType())) {
                examQuestions.setAnswer(examQuestions.getAnswer().replace("|", ","));
            }
            examQuestions.setTestPaperId(examTestPaper.getTestPaperId());
            examQuestionList.add(examQuestions);
        }
        examQuestionsService.saveBatch(examQuestionList);
        for (ExamQuestions examQuestions : examQuestionList) {
            if (QuestionTypeEnum.JUDGE.getType().equals(examQuestions.getType())) {
                examAnswers.add(new ExamAnswers().setQuestionId(examQuestions.getQuestionId()).setKey("A").setValue("正确"));
                examAnswers.add(new ExamAnswers().setQuestionId(examQuestions.getQuestionId()).setKey("B").setValue("错误"));
            } else if (QuestionTypeEnum.SINGLE.getType().equals(examQuestions.getType())
                    || QuestionTypeEnum.MULTIPLE.getType().equals(examQuestions.getType())) {
                if (StringUtils.isNotBlank(examQuestions.getItema())) {
                    examAnswers.add(new ExamAnswers().setQuestionId(examQuestions.getQuestionId()).setKey("A").setValue(examQuestions.getItema()));
                }
                if (StringUtils.isNotBlank(examQuestions.getItemb())) {
                    examAnswers.add(new ExamAnswers().setQuestionId(examQuestions.getQuestionId()).setKey("B").setValue(examQuestions.getItemb()));
                }
                if (StringUtils.isNotBlank(examQuestions.getItemc())) {
                    examAnswers.add(new ExamAnswers().setQuestionId(examQuestions.getQuestionId()).setKey("C").setValue(examQuestions.getItemc()));
                }
                if (StringUtils.isNotBlank(examQuestions.getItemd())) {
                    examAnswers.add(new ExamAnswers().setQuestionId(examQuestions.getQuestionId()).setKey("D").setValue(examQuestions.getItemd()));
                }
                if (StringUtils.isNotBlank(examQuestions.getIteme())) {
                    examAnswers.add(new ExamAnswers().setQuestionId(examQuestions.getQuestionId()).setKey("E").setValue(examQuestions.getIteme()));
                }
            }
        }
        examAnswersService.saveBatch(examAnswers);
        return examTestPaper.getTestPaperId();
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(ExamTestPaper examTestPaper) {
        FanyiUser fanyiUser = SignApiBootstrap.requestFanYiUser();
        boolean remove = super.lambdaUpdate()
                .eq(ExamTestPaper::getTestPaperId, examTestPaper.getTestPaperId())
                .eq(ExamTestPaper::getImei, fanyiUser.getFanyiUserImei())
                .remove();
        if (remove) {
            List<Integer> questionIds = examQuestionsService.lambdaQuery()
                    .select(ExamQuestions::getQuestionId)
                    .eq(ExamQuestions::getTestPaperId, examTestPaper.getTestPaperId())
                    .list().stream().map(ExamQuestions::getQuestionId).collect(Collectors.toList());
            examQuestionsService.removeByIds(questionIds);
            examAnswersService.remove(Wrappers.<ExamAnswers>lambdaQuery().in(ExamAnswers::getQuestionId, questionIds));
        }
        return true;
    }

    public ExamTestPaper get(ExamTestPaper examTestPaper) {
        examTestPaper = super.getById(examTestPaper.getTestPaperId());
        List<ExamQuestions> examQuestionsList = examQuestionsService.lambdaQuery()
                .eq(ExamQuestions::getTestPaperId, examTestPaper.getTestPaperId())
                .list();
        examQuestionsService.bindAnswers(examQuestionsList, null);
        examTestPaper.setExamQuestionsList(examQuestionsList);
        return examTestPaper;
    }
}
